﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Admin;
using SmartSiteManagementSystem.Models.DTO;
using SmartSiteManagementSystem.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{

    [TypeFilter(typeof(LoginAuthorizeAttribute))]
    public class AdminUserController : AdminBaseControllers
    {
        private readonly ILogger<AdminUserController> _logger;
        //注入后台服务
        private readonly IAdminService _adminService;
        public AdminUserController(IAdminService adminService, ILogger<AdminUserController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public JsonResult GetList(string name, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;

            Hashtable param = new Hashtable();
            param.Add("is_deleted", 0);//正常 0 false
            if (!string.IsNullOrEmpty(name))
                param.Add("user_name", name);
            int count = _adminService.GetAdminUserInfoCount(param);
            IList<AdminUserInfo> list = _adminService.GetAdminUserInfoList(param, "", page, rows);

            var data = new
            {
                total = count,
                rows = list
            };
            return Json(data);

        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Access(int id = 0)
        {
            AdminUserInfo adminUserInfo = new AdminUserInfo();
            if (id > 0)
            {
                adminUserInfo = _adminService.GetAdminUserInfoByUserId(id);
            }
            ViewBag.adminUser = adminUserInfo;
            Hashtable param = new Hashtable();
            param.Add("is_deleted", 0);//正常 0 false
            ViewBag.adminGroupList = _adminService.GetAdminGroupList(param, "", 0, 3000);
            return View();
        }

        /// <summary>
        /// 异步操作
        /// </summary>
        /// <param name="AdminUserId"></param>
        /// <param name="UserName"></param>
        /// <param name="UserPwd"></param>
        /// <param name="UserType"></param>
        /// <param name="Email"></param>
        /// <param name="IdCard"></param>
        /// <param name="HandMobile"></param>
        /// <param name="Remark"></param>
        public JsonResult ajaxAccess(int AdminUserId, string UserName, string UserPwd, int UserType, string Email, string IdCard, string HandMobile, string Remark, string AdminGroupIds, string oldIdCard)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 0;
            result.Msg = "操作失败!";

            AdminUserInfo adminUser = null;
            bool success = false;
            int code = -1;
            if (AdminUserId > 0)
            {
                adminUser = _adminService.GetAdminUserInfoByUserId(AdminUserId);
            }
            else
            {
                adminUser = new AdminUserInfo();
                adminUser.StopFlag = false;
            }
            #region 验证及加密证件号码
            if (string.IsNullOrEmpty(IdCard))
            {
                IdCard = "";
            }
            else if (!IdCard.Equals(oldIdCard))
            {
                if (!RegexUtils.VerifyIdCard(IdCard))
                {
                    //证件号码不合法
                    result.IsSuccess = false;
                    result.Code = -2;
                    result.Msg = "证件号码不合法!";
                    return Json(result);
                }
                else
                {
                    IdCard = EncryptionUtils.SHA1Encrypt("SSMS_AdminUserIdCard" + IdCard.Trim(), true, false);
                }
            }
            #endregion
            adminUser.DeleteFlag = false;
            adminUser.Email = Email;
            adminUser.HandMobile = HandMobile;
            adminUser.IdCard = IdCard;
            adminUser.Remark = Remark;
            adminUser.UserName = UserName;
            string pwd = adminUser.UserPwd;
            if (pwd != UserPwd)
                adminUser.UserPwd = EncryptionUtils.GetAdminUserLoginPwd_SHA1(UserName, UserPwd);
            adminUser.UserType = UserType;

            if (AdminUserId > 0)
            {
                success = _adminService.UpdateAdminUserInfo(adminUser);
                if (success)
                {
                    code = 1;
                }
            }
            else
            {
                AdminUserId = _adminService.InsertAdminUserInfo(adminUser);
                success = AdminUserId > 0 ? true : false;
                if (success)
                {
                    code = 1;
                }
            }

            if (success)
            {
                AdminUserGroupRelationInfo adminuserGroupRelationInfo = null;
                string[] idArr = AdminGroupIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                int id = 0;

                _adminService.DeleteAdminUserGroupRelationInfo(AdminUserId);

                foreach (string item in idArr)
                {
                    id = Convert.ToInt32(item);
                    adminuserGroupRelationInfo = new AdminUserGroupRelationInfo();
                    adminuserGroupRelationInfo.AdminUserGroupId = id;
                    adminuserGroupRelationInfo.AdminUserId = AdminUserId;
                    _adminService.InsertAdminUserGroupRelationInfo(adminuserGroupRelationInfo);
                }
            }
            if (code == 1)
            {
                result.IsSuccess = true;
                result.Msg = "操作成功!";
            }
            result.Code = code;
            return Json(result);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="AdminUserId"></param>
        public JsonResult ajaxUpdateState(int AdminUserId)
        {
            AdminUserInfo adminUser = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";

            if (AdminUserId > 0)
            {
                adminUser = _adminService.GetAdminUserInfoByUserId(AdminUserId);
                adminUser.UpdateTime = DateTime.Now;
                adminUser.StopFlag = adminUser.StopFlag ? false : true;
                result.IsSuccess = _adminService.UpdateAdminUserInfo(adminUser);
                if (result.IsSuccess)
                {
                    result.Msg = "操作成功!";
                }

            }
            return Json(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="AdminUserId"></param>
        public JsonResult ajaxDelete(int AdminUserId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (AdminUserId > 0)
            {
                AdminUserInfo adminUser = _adminService.GetAdminUserInfoByUserId(AdminUserId);
                if (adminUser != null)
                {
                    adminUser.DeleteFlag = true;
                    adminUser.UpdateTime = DateTime.Now;
                    result.IsSuccess = _adminService.UpdateAdminUserInfo(adminUser);
                    if (result.IsSuccess)
                    {
                        result.Msg = "操作成功!";
                    }
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 后台用户密码修改
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPwd()
        {
            ViewBag.adminUser = CurrentAdminUser;
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="AdminUserId"></param>
        /// <param name="UserPwd"></param>
        /// <param name="NewPwd"></param>
        /// <param name="NewPwd2"></param>
        public JsonResult DoEditPwd(int AdminUserId, string UserPwd, string NewPwd, string NewPwd2)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Msg = "操作失败!";
            result.Code = 200;
            AdminUserInfo adminUser = null;
            if (AdminUserId > 0)
            {
                adminUser = _adminService.GetAdminUserInfoByUserId(AdminUserId);
            }
            if (adminUser == null)
            {
                result.IsSuccess = false;
                result.Msg = "无法获取当前用户!请重新登入!";
                return Json(result);
            }
            string UserName = adminUser.UserName;
            UserPwd = EncryptionUtils.GetAdminUserLoginPwd_SHA1(UserName, UserPwd);
            if (!adminUser.UserPwd.Equals(UserPwd))
            {
                result.IsSuccess = false;
                result.Msg = "旧密码错误，请重新输入!";
                return Json(result);
            }
            UserPwd = EncryptionUtils.GetAdminUserLoginPwd_SHA1(UserName, NewPwd);

            adminUser.UserPwd = UserPwd;
            bool status = _adminService.UpdateAdminUserInfo(adminUser);
            if (status)
            {
                result.IsSuccess = true;
                result.Msg = "修改成功!";
                return Json(result);
            }
            else
            {
                result.IsSuccess = false;
                result.Msg = "系统异常，修改失败！在重新登录后尝试修改！";
                return Json(result);
            }

        }


    }
}
